import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, In, Like } from 'typeorm';
import { specs } from './specs.entity'; // 修改实体类命名
/**
 * 查询规格列表
 * @param info - 规格列属性
 * @returns 规格列表+总数
 */ 
interface SpecsPageInfo {
  admins_id: number;
  page?: number;
  pageSize?: number;
  name?: string;
  type?: string;
}
@Injectable()
export class SpecsService {
  constructor(
    @InjectRepository(specs) private readonly specsRepository: Repository<specs>, // 修改实体类引用

  ) { }
  /**
   * 删除规格列表
   * @param id - 要删除的规格ID
   * @returns 操作结果
   */
  async delete(id: number): Promise<object> {
    try {
      const result = await this.specsRepository.delete(id);
      return { success: true, ...result };
    } catch (error) {
      throw new Error('Failed to delete specs');
    }
  }

  /**
   * 新增规格列表
   * @param info - 规格信息
   * @returns 操作结果
   */
  async addspecs(info: specs): Promise<object> {
    try {
      const newMenu = this.specsRepository.create(info);
      // console.log(newMenu);
      await this.specsRepository.save(newMenu);
      return newMenu;
    } catch (error) {
      throw new Error('Failed to add menu');
    }
  }

  /**
   * 修改规格列表
   * @param info - 规格信息
   * @returns 操作结果
   */
  async editspecs(info: specs): Promise<object> {
    try {
      const result = await this.specsRepository.update(info.id, info);
      return result;
    } catch (error) {
      throw new Error('Failed to edit menu');
    }
  }
 
  /**
   * 规格列表详情
   * @param id - 规格ID
   * @returns 规格详情
   */
  async oneMenu(id: number): Promise<specs | null> {
    try {
      return await this.specsRepository.findOneBy({ id });
    } catch (error) {
      throw new Error('Failed to fetch menu details');
    }
  }
  /**
* 查询规格列表
* @param info - 规格列属性
* @returns 规格列表+总数
*/
async specsBypage(info: SpecsPageInfo): Promise<any> {
  if(!info.page)return await this.specsRepository.findBy({admins_id:info.admins_id});
  // 输入验证
  if (typeof info.page !== 'number' || typeof info.pageSize !== 'number' || info.page < 1 || info.pageSize < 1) {
    throw new Error('Invalid pagination parameters: page and pageSize must be positive numbers');
  }

  if (info.name && typeof info.name !== 'string') {
    throw new Error('Invalid parameter: name must be a string');
  }

  if (info.type && typeof info.type !== 'string') {
    throw new Error('Invalid parameter: type must be a string');
  }

  // 构建查询条件
  const queryConditions: any = {};
  if (info.name) {
    queryConditions.name = Like(`%${sanitizeInput(info.name)}%`);
  }

  if (info.type) {
    queryConditions.type = info.type;
  }
  
  if (info.admins_id) {
    queryConditions.admins_id = info.admins_id;
  }
  try {
    const [posts, total] = await this.specsRepository.findAndCount({
      where: queryConditions,
      skip: (info.page - 1) * info.pageSize,
      order: {
        sort_order: 'DESC',
      },
      take: info.pageSize,
    });

    return {
      data: posts,
      total,
      page: info.page,
      pageSize: info.pageSize,
    };
  } catch (error) {
    console.error('Error fetching specs:', error); // 记录错误日志
    throw new Error('Failed to fetch specs');
  }
}
}
/**
 * 辅助函数：对用户输入进行转义，防止 SQL 注入
 * @param input - 用户输入
 * @returns 转义后的字符串
 */
function sanitizeInput(input: string): string {
  return input.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); // 转义特殊字符
}
